package GUILayer;

import ControlLayer.PersonCtr;
import ControlLayer.StatisticsCtr;
import ModelLayer.RealException;
import ModelLayer.Sale;
import ModelLayer.SalesRecords;

import java.awt.BorderLayout;

import javax.swing.BorderFactory;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.BoxLayout;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

import java.awt.GridLayout;
import java.awt.FlowLayout;
import java.awt.CardLayout;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class CustomerStatisticUI extends JPanel {

	private static final long serialVersionUID = 1L;

	private JTextField showIdField;
	private JTextField showNameField;

	private DefaultTableModel tableModel;
	private JTable table;

	private JPanel showStatistic;
	private JPanel searchStatistic;

	private JPanel statisticContainer;
	private JTextField txtCustomerId;
	private JTextField txtMonthYear;

	private SalesRecords salesRecords;
	private PersonCtr personCtr;
	private StatisticsCtr statisticsCtr;

	public CustomerStatisticUI() {
		salesRecords = SalesRecords.getInstance();
		personCtr = new PersonCtr();
		statisticsCtr = new StatisticsCtr();
		initialize();
	}

	public void initialize() {

		tableModel = new DefaultTableModel() {
			private static final long serialVersionUID = 1L;

			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		tableModel.addColumn("ID");
		tableModel.addColumn("Price");
		tableModel.addColumn("Date");

		this.setLayout(new BorderLayout(0, 0));

		statisticContainer = new JPanel();
		this.add(statisticContainer);
		statisticContainer.setLayout(new CardLayout(0, 0));

		searchStatistic = new JPanel();
		statisticContainer.add(searchStatistic, "searchStatistic");
		searchStatistic.setLayout(new BorderLayout(0, 0));

		JPanel searchStatisticPanel = new JPanel();
		searchStatisticPanel.setBorder(BorderFactory
				.createTitledBorder("Search Customer Statistics"));
		searchStatistic.add(searchStatisticPanel, BorderLayout.CENTER);
		searchStatisticPanel.setLayout(new BorderLayout(0, 0));

		JPanel searchStatisticInfo = new JPanel();
		searchStatisticPanel.add(searchStatisticInfo);
		searchStatisticInfo.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

		JLabel lblCustomerId = new JLabel("Customer ID");
		searchStatisticInfo.add(lblCustomerId);

		txtCustomerId = new JTextField();
		searchStatisticInfo.add(txtCustomerId);
		txtCustomerId.setColumns(5);

		JLabel label = new JLabel("Month/Year (mm/yyyy)");
		searchStatisticInfo.add(label);

		txtMonthYear = new JTextField();
		searchStatisticInfo.add(txtMonthYear);
		txtMonthYear.setColumns(10);

		JButton btnShowButton = new JButton("Show");
		btnShowButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int[] result;
				try {
					result = getMonthYear(txtMonthYear.getText());
					showStatistic(Integer.parseInt(txtCustomerId.getText()),
							result[0], result[1]);
				} catch (RealException e1) {
					JOptionPane.showMessageDialog(null, e1.getError(), "Error",
							JOptionPane.ERROR_MESSAGE);
				}

			}
		});
		searchStatisticInfo.add(btnShowButton);

		showStatistic = new JPanel();
		statisticContainer.add(showStatistic, "showStatistic");
		showStatistic.setLayout(new GridLayout(0, 2, 0, 0));

		JPanel showStatisticInfoContainer = new JPanel();
		showStatistic.add(showStatisticInfoContainer);

		showStatisticInfoContainer.setLayout(new BoxLayout(
				showStatisticInfoContainer, BoxLayout.Y_AXIS));

		JPanel showStatisticInfoPanel = new JPanel();
		showStatisticInfoContainer.add(showStatisticInfoPanel);
		showStatisticInfoPanel.setBorder(BorderFactory
				.createTitledBorder("Customer Statistic"));
		;
		showStatisticInfoPanel.setLayout(new BoxLayout(showStatisticInfoPanel,
				BoxLayout.X_AXIS));

		JPanel showStatisticLeft = new JPanel();
		showStatisticInfoPanel.add(showStatisticLeft);
		showStatisticLeft.setLayout(new GridLayout(0, 1, 0, 0));

		JPanel showIdLabelPanel = new JPanel();
		showIdLabelPanel.setLayout(new BoxLayout(showIdLabelPanel,
				BoxLayout.X_AXIS));
		showStatisticLeft.add(showIdLabelPanel);

		JLabel showIdLabel = new JLabel("ID");
		showIdLabelPanel.add(showIdLabel);
		showIdLabel.setHorizontalAlignment(SwingConstants.CENTER);

		JPanel showNameLabelPanel = new JPanel();
		showNameLabelPanel.setLayout(new BoxLayout(showNameLabelPanel,
				BoxLayout.X_AXIS));
		showStatisticLeft.add(showNameLabelPanel);

		JLabel showNameLabel = new JLabel("Customer");
		showNameLabelPanel.add(showNameLabel);
		showNameLabel.setHorizontalAlignment(SwingConstants.CENTER);

		JPanel showStatisticRight = new JPanel();
		showStatisticInfoPanel.add(showStatisticRight);
		showStatisticRight.setLayout(new BoxLayout(showStatisticRight,
				BoxLayout.Y_AXIS));

		JPanel showIdFieldPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
		showStatisticRight.add(showIdFieldPanel);

		showIdField = new JTextField();
		showIdFieldPanel.add(showIdField);
		showIdField.setHorizontalAlignment(SwingConstants.CENTER);
		showIdField.setEditable(false);
		showIdField.setColumns(5);

		JPanel showNameFieldPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
		showStatisticRight.add(showNameFieldPanel);

		showNameField = new JTextField();
		showNameFieldPanel.add(showNameField);
		showNameField.setHorizontalAlignment(SwingConstants.CENTER);
		showNameField.setEditable(false);
		showNameField.setColumns(20);

		JPanel showBottomMenu = new JPanel();
		showStatisticInfoContainer.add(showBottomMenu);
		showBottomMenu.setLayout(new BorderLayout(0, 0));

		JPanel showBottomMenuRight = new JPanel();
		showBottomMenu.add(showBottomMenuRight, BorderLayout.CENTER);

		JPanel showBottomMenuLeft = new JPanel();
		showBottomMenu.add(showBottomMenuLeft, BorderLayout.WEST);

		JButton showBtnBack = new JButton("Back");
		showBtnBack.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				CardLayout cl = (CardLayout) (statisticContainer.getLayout());
				cl.show(statisticContainer, "searchStatistic");
			}
		});
		showBottomMenuLeft.add(showBtnBack);

		JPanel showStatisticItems = new JPanel();
		showStatistic.add(showStatisticItems);
		showStatisticItems.setBorder(BorderFactory.createTitledBorder("Sales"));
		showStatisticItems.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

		JScrollPane scrollPane_1 = new JScrollPane();
		showStatisticItems.add(scrollPane_1);

		table = new JTable(tableModel);

		table.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
		table.setAutoCreateRowSorter(true);

		scrollPane_1.setViewportView(table);
	}

	protected void showStatistic(int id, int month, int year) {
		try {
			showNameField.setText(personCtr.getCustomer(id).getName());
			showIdField.setText(String.valueOf(id));

			SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
			formatter.setLenient(false);
			tableModel.setRowCount(0);
			for (Sale sale : salesRecords.getSalesRecords()) {
				if (sale.getCustomer().getId() == id
						&& sale.getMonth() == month && sale.getYear() == year) {
					tableModel.addRow(new Object[] {
							sale.getId(),
							Double.valueOf(new DecimalFormat("#.##")
									.format(sale.getFinalPrice())),
							formatter.format(sale.getStartDay()) });
				}
			}

			double totalPrice = statisticsCtr.getTotalCustomer(id, month, year);
			String[] space = { "", "", "" };
			String[] totalPriceRow = {
					"",
					"Total Price:",
					Double.toString(Double.valueOf(new DecimalFormat("#.##")
							.format(totalPrice))) };
			tableModel.addRow(space);
			tableModel.addRow(space);
			tableModel.addRow(totalPriceRow);
			CardLayout cl = (CardLayout) (statisticContainer.getLayout());
			cl.show(statisticContainer, "showStatistic");
		} catch (RealException e) {
			JOptionPane.showMessageDialog(null, e.getError(), "Error",
					JOptionPane.ERROR_MESSAGE);
		}
	}

	public int[] getMonthYear(String input) throws RealException {
		int[] result = { 0, 0 };
		if (input.matches("(0[1-9]|1[0-2])/[1-9][0-9][0-9][0-9]")) {
			try {
				result[0] = Integer.parseInt(input.substring(0, 2));
				result[1] = Integer.parseInt(input.substring(3, 7));
			} catch (NumberFormatException nFE) {
				throw new RealException("Field value invalid");
			}
		} else {
			throw new RealException("Field value invalid");
		}
		return result;
	}

}
